from pathlib import Path

from view.base import TableFrameBase
from qfluentwidgets import StateToolTip, InfoBar
from components import OpenFileDialog
from common import MergeToPdfThread
from ..base import ReturnView


class MergeToPdfView(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.tableFrame = TableFrameBase(self)
        self.tableFrame.lineEdit.setReadOnly(True)
        self.tableFrame.setTitle('PDF合成')
        self.tableFrame.setHeaders(['文件名称', '完整路径', '文件类型'])

        self.stateToolTip = StateToolTip('合成PDF', '正在批量合成PDF，请稍后...', parent=self)
        self.stateToolTip.hide()

        self.merge_thread = MergeToPdfThread(self)

        self.vBox.addWidget(self.tableFrame)
        self.initEvent()

    def initEvent(self):
        self.returnButton.clicked.connect(self.returnButton_event)
        self.tableFrame.added.connect(self.added_event)
        self.tableFrame.saved.connect(self.saved_event)
        self.tableFrame.started.connect(self.started_event)

        self.merge_thread.started.connect(self.started_thread)
        self.merge_thread.error.connect(self.error_thread)
        self.merge_thread.finished.connect(self.finished_thread)

    def resizeEvent(self, event):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)

    def returnButton_event(self):
        self.tableFrame.clear()
        self.returned.emit()

    def added_event(self):
        files = OpenFileDialog(self).getOpenFileNames(filter='PDF文件(*.pdf)')[0]
        for file in files:
            if file in self.tableFrame.getColumnValues(1):
                InfoBar.warning('提示', file + '已存在', duration=3000, parent=self)
                continue
            self.tableFrame.addItem([Path(file).name, file, Path(file).suffix])

    def saved_event(self):
        file = OpenFileDialog(self).getSaveFileName(_dir='./merge_to_pdf.pdf', filter='PDF文件(*.pdf)')[0]
        self.tableFrame.setLineText(file)

    def started_event(self):
        files = self.tableFrame.getColumnValues(1)
        save_path = self.tableFrame.lineText()
        if save_path == '':
            return
        if len(files) == 0:
            InfoBar.warning('提示', '请选择pdf文件', duration=3000, parent=self)
            return
        self.merge_thread.set_value(files, save_path)
        self.merge_thread.start()

    def started_thread(self):
        self.stateToolTip.show()

    def error_thread(self, msg):
        InfoBar.warning('错误', msg, duration=5000, parent=self)

    def finished_thread(self):
        self.stateToolTip.hide()
        InfoBar.success('提示', '合成完毕', duration=3000, parent=self)
